package org.ring.common.utils.reflect;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * @since 2024-10-28 16:23
 */
public class ServiceDescriptor {

    private final Class<?> interfaceClass;
    private final String interfaceName;

    private final Map<String, Map<String, MethodDescriptor>> methodDescriptorMapping = new HashMap<>();
    private final Map<Method,MethodDescriptor> methodMethodDescriptorMap = new HashMap<>();

    public ServiceDescriptor(Class<?> interfaceClass){
        this.interfaceClass = interfaceClass;
        this.interfaceName = interfaceClass.getName();
        this.parseMethodDescriptors();
    }

    public String getInterfaceName(){
        return interfaceName;
    }

    private void parseMethodDescriptors(){
        Method[] methods = this.interfaceClass.getMethods();
        for (Method method : methods) {
            MethodDescriptor methodDescriptor = new MethodDescriptor(method);
            String name = method.getName();
            Map<String, MethodDescriptor> descriptorMap = methodDescriptorMapping.get(name);
            if(descriptorMap == null){
                descriptorMap = new HashMap<>();
                methodDescriptorMapping.put(name,descriptorMap);
            }
            methodMethodDescriptorMap.put(method,methodDescriptor);
            descriptorMap.put(methodDescriptor.getParameterDescriptor(),methodDescriptor);
        }
    }

    public MethodDescriptor getMethod(String methodName,String paramDescriptor){
        Map<String, MethodDescriptor> descriptorMap = methodDescriptorMapping.get(methodName);
        if (descriptorMap == null) {
            return null;
        }
        return descriptorMap.get(paramDescriptor);
    }

    public MethodDescriptor getMethod(Method method){
        return methodMethodDescriptorMap.get(method);
    }



}
